package com.example.adminLite.service;

import com.example.adminLite.exception.WebRunException;
import com.example.adminLite.model.Music;
import com.example.adminLite.repository.MusicRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class MusicService {

    private final MusicRepository MusicRepository;

    public MusicService(MusicRepository MusicRepository) {
        this.MusicRepository = MusicRepository;
    }

    public Music save(Music Music)
    {
         Music existMusic = this.MusicRepository.findMusicByMusicName(Music.getMusicName());
         if (!Objects.isNull(existMusic) && !Objects.equals(existMusic.getId(), Music.getId())){
             throw new WebRunException("歌曲名已经存在");
         }
        return this.MusicRepository.save(Music);
    }

    public List<Music> index()
    {
        return this.MusicRepository.findAll();
    }

    public void del(long id) {
        this.MusicRepository.deleteById(id);
    }

    public Music findById(long id) {
        Optional<Music> byId = this.MusicRepository.findById(id);
        return byId.orElse(null);
    }
}
